package com.fangdd.logtrace.jms;

import com.fangdd.logtrace.BoundsLog;
import com.fangdd.logtrace.TraceId;
import com.fangdd.logtrace.TraceRootGenerator;
import com.fangdd.logtrace.TraceWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.jms.JMSException;
import javax.jms.Message;
import java.util.concurrent.Callable;

/**
 * Created by sulong on 16-9-12.
 */
public class TraceIdJmsReceiverWrapper {
    private static final Logger LOGGER = LoggerFactory.getLogger(TraceIdJmsReceiverWrapper.class);

    public static void wrap(Message message, final String interfaceName, final Runnable runnable) {
        String traceIdFromMessage = null;
        try {
            traceIdFromMessage = message.getStringProperty(TraceIdHeader.HEADER_NAME);
        } catch (JMSException e) {
            LOGGER.error("fail to get " + TraceIdHeader.HEADER_NAME + " property from message", e);
        }

        TraceId traceId = traceIdFromMessage  == null
                ? new TraceId(TraceRootGenerator.newUUIDRoot())
                : new TraceId(traceIdFromMessage);

        try {
            TraceWith.run(traceId, new Callable<Object>() {
                @Override
                public Object call() throws Exception {
                    long startTime = System.currentTimeMillis();
                    BoundsLog.calleeIn(LOGGER, interfaceName);
                    try {
                        runnable.run();
                        BoundsLog.calleeOut(LOGGER, interfaceName, true, System.currentTimeMillis() - startTime);
                    } catch (Exception e) {
                        BoundsLog.calleeOut(LOGGER, interfaceName, false, System.currentTimeMillis() - startTime);
                    }
                    return null;
                }
            });
        } catch (Exception e) {
            LOGGER.error("unexpected exception", e);
        }
    }
}
